import { getHttp,http } from './http';
import { blog } from './protobuf-loader';
import { getToken } from '@/utils/auth';
import {formatTimestamp} from "@/utils/time";

// 获取proto类型
const BlogListRequest = blog.BlogListRequest;
const BlogListResponse = blog.BlogListResponse;
const BlogDetailRequest = blog.BlogDetailRequest;
const BlogDetailResponse = blog.BlogDetailResponse;
const LikeRequest = blog.LikeRequest;
const LikeResponse = blog.LikeResponse;
const CommentRequest = blog.CommentRequest;
const CommentResponse = blog.CommentResponse;

/**
 * 获取博客列表
 * @param {Object} params 查询参数
 * @returns {Promise<{blogs: Array, total: number}>}
 */
export const getBlogList = async (params = { page: 1, pageSize: 10 }) => {
    const request = new BlogListRequest();
    request.setToken(getToken());
    request.setPage(params.page);
    request.setPageSize(params.pageSize);
    const responseData = await http.post('/blog/list',
      request.serializeBinary());
    const response = BlogListResponse.deserializeBinary(responseData.data);

    if (responseData.status !== 200){
        throw "请求失败"
    }
    if (!response.getSuccess()) {
        throw response.getMessage()
    }

    return {
      blogs: response.getBlogsList().map(log => ({
        id: log.getId(),
        title: log.getTitle(),
        date: log.getDate(),
        preview: log.getPreview(),
        likes: log.getLikes(),
        view_count: log.getViewCount(),
        author: {
          email: log.getAuthor().getEmail(),
          name: log.getAuthor().getName(),
          avatar: log.getAuthor().getAvatar()
        }
      })),
      total: response.getTotal()
    };
  
};

/**
 * 获取博客详情
 * @param {string} id 博客ID
 * @returns {Promise<Object>}
 */
export const getBlogDetail = async (id,page = 1,pagesize = 10) => {
    const request = new BlogDetailRequest();
    request.setToken(getToken());
    request.setId(id);
    request.setPage(page);
    request.setPageSize(pagesize);
    
    const responseData = await http.post('/blog/detail',
      request.serializeBinary());
    
    const response = BlogDetailResponse.deserializeBinary(responseData.data);
    if (responseData.status !== 200){
        throw "请求失败"
    }
    if (!response.getSuccess()) {
        throw response.getMessage()
    }

    const log = response.getBlog();
    return {
      id: log.getId(),
      title: log.getTitle(),
      content: log.getContent(),
      date: log.getDate(),
      likes: log.getLikes(),
      author: {
        email: log.getAuthor().getEmail(),
        name: log.getAuthor().getName(),
        avatar: log.getAuthor().getAvatar()
      },
      comments: log.getCommentsList().map(comment => ({
        id: comment.getId(),
        content: comment.getContent(),
        author: {
            email: comment.getAuthor().getEmail(),
            name: comment.getAuthor().getName(),
            avatar: comment.getAuthor().getAvatar()
          },
        time: formatTimestamp(comment.getCreatedAt()),
        likes: comment.getLikes(),
        parent_id: comment.getParentId(),
        comment_total: comment.getCommentTotal()
      })),
      comment_total: log.getCommentTotal()
    };
};

/**
 * 提交点赞
 * @param {string} blogId 博客ID
 * @returns {Promise<{success: boolean}>}
 */
export const submitLike = async (blogId) => {
    const request = new LikeRequest();
    request.setToken(getToken());
    request.setBlogId(blogId);
    const responseData = await http.post('/blog/like',
      request.serializeBinary());

    const response = LikeResponse.deserializeBinary(responseData.data);
    // 打印响应内容
    console.log("response.success:", response.getSuccess());
    console.log("responseData.status:", responseData.status);
    console.log("response.message:", response.getMessage && response.getMessage());

    // if (!response.getSuccess()) {
    //     throw new Error(response.getMessage());
    // }
    if (responseData.status !== 200){
        throw "请求失败"
    }

    if (!response.getSuccess()) {
        throw response.getMessage()
        // throw new Error(response.getMessage());
    }
    
    return { success: response.getSuccess() ,
                message: response.getMessage()
    };
};

/**
 * 提交评论
 * @param {string} blogId 博客ID
 * @param {string} content 评论内容
 * @param {string} parentId 父评论ID
 * @returns {Promise<{success: boolean, comment: Object}>}
 */
export const submitComment = async (blogId, content, parentId = "") => {

    const request = new CommentRequest();
    request.setToken(getToken());
    request.setBlogId(blogId);
    request.setContent(content);
    request.setParentId(parentId);
    const responseData = await http.post('/blog/submitcomment',
      request.serializeBinary());
    const response = CommentResponse.deserializeBinary(responseData.data);
    if (responseData.status !== 200){
        throw "请求失败"
    }
    if (!response.getSuccess()) {
        throw response.getMessage()
    }

    return {
      comment: {
        id: response.getComment().getId(),
        content: response.getComment().getContent(),
        author: {
          id: response.getComment().getAuthor().getEmail(),
          name: response.getComment().getAuthor().getName(),
          avatar: response.getComment().getAuthor().getAvatar()
        },
        time: formatTimestamp(response.getComment().getCreatedAt()),
        parent_id: response.getComment().getParentId()
      }
    };
};
//  获取评论列表
export const getSubComments = async (blogId, parentId, page, pageSize) =>{
    const request = new blog.BlogCommentRequest();
    request.setToken(getToken());
    request.setBlogId(blogId);
    request.setParentId(parentId);
    request.setPage(page);
    request.setPageSize(pageSize);
    const responseData = await http.post('/blog/getcomments',
        request.serializeBinary());
    const response = blog.BlogCommentResponse.deserializeBinary(responseData.data);

    if (responseData.status !== 200){
        throw "请求失败"
    }
    if (!response.getSuccess()) {
        throw response.getMessage()
    }
    
    return {
        list: response.getCommentsList().map(comment => ({
            id: comment.getId(),
            content: comment.getContent(),
            author: {
                email: comment.getAuthor().getEmail(),
                name: comment.getAuthor().getName(),
                avatar: comment.getAuthor().getAvatar()
                },
            time: formatTimestamp(comment.getCreatedAt()),
            likes: comment.getLikes(),
            parent_id: comment.getParentId(),
            comment_total: comment.getCommentTotal()
            })),
        total: response.getTotal()
    }
    
};

export const getUserBlogs = async (email,published, page, pagesize) => {
    const request = new blog.UserBlogListRequest();
    request.setToken(getToken());
    request.setEmail(email);
    request.setPublished(published);
    request.setPage(page);
    request.setPageSize(pagesize);
    const responseData = await http.post('/blog/userblogs',
        request.serializeBinary());
    const response = blog.BlogListResponse.deserializeBinary(responseData.data);
    if (responseData.status !== 200){
        throw "请求失败"
    }
    if (!response.getSuccess()) {
        throw response.getMessage()
    }
    return {
        blogs: response.getBlogsList().map(log => ({
            id: log.getId(),
            title: log.getTitle(),
            date: log.getDate(),
            preview: log.getPreview(),
            likes: log.getLikes(),
            view_count: log.getViewCount(),
            author: {
              email: log.getAuthor().getEmail(),
              name: log.getAuthor().getName(),
              avatar: log.getAuthor().getAvatar()
            }
          })),
        total: response.getTotal()
    }
};

export const deleteBlog = async (blogId) => {
    const request = new blog.DeleteBlogRequest();
    request.setToken(getToken());
    request.setBlogId(blogId);
    const responseData = await http.post('/blog/delete',
        request.serializeBinary());
    const response = blog.DeleteBlogResponse.deserializeBinary(responseData.data);
    if (responseData.status !== 200){
        throw "请求失败"
    }
    if (!response.getSuccess()) {
        throw response.getMessage()
    }
    return {
        success: response.getSuccess(),
        message: response.getMessage()
    }
};
export const createBlog = async ( blogId, title, content, published ) => {
    const request = new blog.CreateBlogRequest();
    request.setToken(getToken());
    request.setBlogId(blogId);
    request.setTitle(title);
    request.setContent(content);
    request.setPublished(published);
    const responseData = await http.post('/blog/create',
        request.serializeBinary());
    console.log("请求成功");
    const response = blog.CreateBlogResponse.deserializeBinary(responseData.data);
    if (responseData.status !== 200){
        console.log(responseData.status);
        throw "请求失败"
    }
    if (!response.getSuccess()) {
        console.log("response:flase");
        throw response.getMessage()
    }
    return {
        success: response.getSuccess(),
        message: response.getMessage()
    }
};

export const editBlog = async ( blogId) => {
    const request = new blog.EditBlogRequest();
    request.setToken(getToken());
    request.setBlogId(blogId);
    const responseData = await http.post('/blog/edit',
        request.serializeBinary());
    const response = blog.EditBlogResponse.deserializeBinary(responseData.data);
    if (responseData.status !== 200){
        throw "请求失败"
    }
    if (!response.getSuccess()) {
        throw response.getMessage()
    }
    return {
        success: response.getSuccess(),
        message: response.getMessage(),
        blogId: response.getBlogId(),
        title: response.getTitle(),
        content: response.getContent(),
        published: response.getPublished()
    }
};

export const getLikedBlogs = async (email, page, pagesize) => {
    const request = new blog.LikedBlogListRequest();
    request.setToken(getToken());
    request.setEmail(email);
    request.setPage(page);
    request.setPageSize(pagesize);
    const responseData = await http.post('/blog/likedblogs',
        request.serializeBinary());
    const response = blog.LikedBlogListResponse.deserializeBinary(responseData.data);
    if (responseData.status !== 200){
        throw "请求失败"
    }
    if (!response.getSuccess()) {
        throw response.getMessage()
    }
    return {
        blogs: response.getBlogsList().map(log => ({
            id: log.getId(),
            title: log.getTitle(),
            date: log.getDate(),
            preview: log.getPreview(),
            likes: log.getLikes(),
            view_count: log.getViewCount(),
            author: {
                email: log.getAuthor().getEmail(),
                name: log.getAuthor().getName(),
                avatar: log.getAuthor().getAvatar()
            }
        })),
        total: response.getTotal()
    }
};

export const deleteLikeBlog = async (blogId) => {
    const request = new blog.DeleteLikeBlogRequest();
    request.setToken(getToken());
    request.setBlogId(blogId);
    const responseData = await http.post('/blog/deletelike',
        request.serializeBinary());
    const response = blog.DeleteLikeBlogResponse.deserializeBinary(responseData.data);
    if (responseData.status !== 200){
        throw "请求失败"
    }
    if (!response.getSuccess()) {
        throw response.getMessage()
    }
    return {
        success: response.getSuccess(),
        message: response.getMessage()
    }
}